package com.blb.demo;

public class ThreadLocalDemo {

    //共享一个变量
    private static int count = 0;

    //线程本地变量
    private static ThreadLocal<Integer> threadLocal = new ThreadLocal(){
        @Override
        protected Object initialValue() {
            return 0;
        }
    };

    public static void main(String[] args) {
        new Thread(() -> {
            //对成员变量的修改，对其它线程有影响
            ThreadLocalDemo.count++;
            System.out.println(Thread.currentThread().getName() +"访问的count是：" + count);
            //对threadlocal变量的修改，对其它线程没有影响
            threadLocal.set(threadLocal.get() + 1);
            System.out.println(Thread.currentThread().getName() +"访问的threadLocal是：" + threadLocal.get());
        }).start();
        new Thread(() -> {
            ThreadLocalDemo.count++;
            System.out.println(Thread.currentThread().getName() +"访问的count是：" + count);
            threadLocal.set(threadLocal.get() + 1);
            System.out.println(Thread.currentThread().getName() +"访问的threadLocal是：" + threadLocal.get());
        }).start();
        new Thread(() -> {
            ThreadLocalDemo.count++;
            System.out.println(Thread.currentThread().getName() +"访问的count是：" + count);
            threadLocal.set(threadLocal.get() + 1);
            System.out.println(Thread.currentThread().getName() +"访问的threadLocal是：" + threadLocal.get());
        }).start();
    }
}
